﻿using System;
using System.Collections.Generic;
using System.Linq;
using SimpleBlog.Models;
using SimpleBlog.Infrastructure.Repositories;
using SimpleBlog.Infrastructure.Database;

namespace SimpleBlog.Infrastructure.Repositories
{
    public class UserRepository : Repository<User>, IUserRepository
    {
        protected override Func<User, object> DefaultOrderBy
        {
            get
            {
                return x => x.UserId;
            }
        }

        public UserRepository(SbContext context) : base(context) { }

        public override void Add(User entity)
        {
            var exists = DefaultSet.Any(x => x.Login.Equals(entity.Login) || x.Email.Equals(entity.Email, StringComparison.InvariantCultureIgnoreCase));
            if (!exists)
            {
                base.Add(entity);
            }
        }

        public override User FindById(int id)
        {
            return (from entity in DefaultSet
                    where id == entity.UserId
                    select entity).SingleOrDefault();
        }

        public override IEnumerable<User> FindById(params int[] ids)
        {
            return from entity in DefaultSet
                   where ids.Contains(entity.UserId)
                   select entity;
        }

        public User FindByLogin(string login)
        {
            return this.Search(x => x.Login == login).SingleOrDefault();
        }
    }
}